//
//  LBScrollView.m
//  ScrollView
//
//  Created by ios on 16/3/18.
//  Copyright © 2016年 你个LB. All rights reserved.
//

#import "LBPageTurnView.h"

#import "LBPageControl.h"

@interface LBPageTurnView () <UIScrollViewDelegate>
{
    // 当前视图的尺寸
    CGSize _selfFrame;
    
    // 分页控件
    LBPageControl * _pageCtrl;
    
    // 定时器
    NSTimer * _timer;
    
    NSInteger _currentPage;
}

// 是否定时滑动
@property (nonatomic , assign) BOOL timingMove;

@property (nonatomic , strong) UIScrollView * scrollView;

@end

@implementation LBPageTurnView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 当前页面的大小赋值给_selfFrame
        _selfFrame = frame.size;
        
        // 初始化滑动视图
        [self _initScrollView];
        
        // 初始化分页控件
        [self _initPageController];
    }
    return self;
}

// 添加一个定时器
- (void)addTimer {
    
    _timer = [NSTimer timerWithTimeInterval:_pageTurnTime target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
}

/**
 *  移除定时器
 */
- (void)removeTimer
{
    
    [_timer invalidate];
    _timer = nil;
}

// 切换到下一张图片
- (void)nextImage
{
    // 计算scrollView滚动的位置
    CGFloat offsetX = _scrollView.contentOffset.x + _selfFrame.width;
    [_scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
}

// 初始化滑动视图
- (void)_initScrollView {
    _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _scrollView.backgroundColor = [UIColor whiteColor];
    // 隐藏水平导航栏
    _scrollView.showsHorizontalScrollIndicator = NO;
    // 设置分页
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    [self addSubview:_scrollView];
}

// 初始化分页控件
- (void)_initPageController {
    _pageCtrl = [[LBPageControl alloc] initWithFrame:CGRectMake(_selfFrame.width - 60 - 20, _selfFrame.height - 20 - 20, 60, 20)];
    _pageCtrl.currentPage = 0;
//    [_pageCtrl addTarget:self action:@selector(pageControlAction:) forControlEvents:UIControlEventValueChanged];
    [self insertSubview:_pageCtrl aboveSubview:_scrollView];
    [self addSubview:_pageCtrl];
}

// 设置分页控件的frame
- (void)setPageControlFrame:(CGRect)pageControlFrame {
        _pageCtrl.frame = pageControlFrame;
}

// 分页控件的交互性
- (void)setPageControlEnabled:(BOOL)pageControlEnabled {
    _pageCtrl.enabled = pageControlEnabled;
}

// 设置页面翻转时间
- (void)setPageTurnTime:(CGFloat)pageTurnTime {
    
    NSLog(@"3333%f",pageTurnTime);
    
    if (_pageTurnTime != pageTurnTime) {
        _pageTurnTime = pageTurnTime;
        [self addTimer];
    }
    
        // 设置可以定时器开始
        _timingMove = YES;
}

// 分页控件的点击事件
//- (void)pageControlAction:(UIPageControl *)pageControl {
//    // 移除定时器
//    if (_timer) {
//        [self removeTimer];
//    }
//    //设置视图的偏移量
//    [_scrollView setContentOffset:CGPointMake((pageControl.currentPage + 1) * _selfFrame.width, 0) animated:YES];
//    // 添加定时器
//    if (_timer == nil && _timingMove) {
//        [self addTimer];
//    }
//}

// 图片数组的set方法
- (void)setImageNames:(NSArray *)imageNames {
    
    // 把这个图片数组添加首尾图片
    imageNames = [self addHeadAndTailImage:imageNames];
    _imageNames = imageNames;
    
    // 设置滑动视图的实际尺寸
    _scrollView.contentSize = CGSizeMake(_selfFrame.width * imageNames.count, _selfFrame.height);
    // 设置滑动视图的偏移量
    _scrollView.contentOffset = CGPointMake(_selfFrame.width, 0);
    // 设置分页控件的页数
    _pageCtrl.numberOfPages = imageNames.count - 2;
    
    for (int i = 0; i < imageNames.count; i ++) {
        UIButton * ImageViewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        ImageViewBtn.frame = CGRectMake(i * _selfFrame.width, 0, _selfFrame.width, _selfFrame.height);
        [ImageViewBtn setBackgroundImage:[UIImage imageNamed:imageNames[i]] forState:UIControlStateNormal];
        [ImageViewBtn setBackgroundImage:[UIImage imageNamed:imageNames[i]] forState:UIControlStateHighlighted];
        ImageViewBtn.tag = i + 100;
        [ImageViewBtn addTarget:self action:@selector(imageViewBtnAction:) forControlEvents:UIControlEventTouchUpInside];
         [_scrollView addSubview:ImageViewBtn];
        
    }
}



// 数组的首尾添加图片（尾添加到首，首添加到尾）
- (NSArray *)addHeadAndTailImage:(NSArray *)array {
    NSMutableArray * mutableImageNames = [array mutableCopy];
    
    NSString * firstImageName = [array firstObject];
    NSString * lastImageName = [array lastObject];
    [mutableImageNames insertObject:firstImageName atIndex:mutableImageNames.count];
    [mutableImageNames insertObject:lastImageName atIndex:0];
    
    return mutableImageNames;
}

// 在手指将要滑动时移除定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (_timer) {
        [self removeTimer];
    }
}

// 在手指已经停止拖住的时候添加定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (_timer == nil && _timingMove) {
        [self addTimer];
    }
}


//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//
//    [self updatePageCtrlWithContentOffset:scrollView.contentOffset.x];
//
//}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self updatePageCtrlWithContentOffset:scrollView.contentOffset.x];
}

- (void)updatePageCtrlWithContentOffset:(CGFloat)contentOffset_x{
    // 一定要用float类型，非常重要
    CGFloat index = contentOffset_x / (_selfFrame.width) ;
    if (index >= _imageNames.count - 1) {
        //设置视图的偏移量
        _scrollView.contentOffset = CGPointMake(_selfFrame.width, 0);
        _pageCtrl.currentPage = 0;
    }else if(index <= 0){
        _scrollView.contentOffset = CGPointMake((_imageNames.count - 2) *_selfFrame.width, 0);
        _pageCtrl.currentPage = _imageNames.count - 2;
    } else {
        //设置_pageCtrl显示的页数
        _pageCtrl.currentPage = index-1;
    }
    
    if (_currentPage != _pageCtrl.currentPage) {
        _currentPage = _pageCtrl.currentPage;
        // 判断代理是否实现了代理方法
        if ([self.delegate respondsToSelector:@selector(pageTurnViewPageDidChange:withCurrentPage:)]) {
            // 判断页面
            
            // 通知代理
            [self.delegate pageTurnViewPageDidChange:self withCurrentPage:_currentPage];
        }
    }
}



#pragma 页面点击事件
- (void)imageViewBtnAction:(UIButton *)button {
    // 判断代理是否实现了代理方法
    if ([self.delegate respondsToSelector:@selector(pageTurnViewClickDidView:withClickPageNumber:)]) {
        // 判断点击的页面
        NSInteger clickPageNumber = button.tag - 100;
        // 通知代理
        [self.delegate pageTurnViewClickDidView:self withClickPageNumber:clickPageNumber];
    }
}

@end
